<!DOCTYPE html>
<html lang=zh>
<head>
    <meta name="baidu-site-verification" content="lKl7jYajUz" />
    <meta charset="utf-8">
    
    <title>ElasticSearch JAVA API基础学习------Elasticsearch学习（二） | 迷失的男孩</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="keywords" content="火龙战士,zhengweishan,郑伟山的博客，bolg,博客">
    <meta name="description" content="ElasticSearch JAVA API基础学习——Elasticsearch学习（二）在上一篇博客中（Elasticsearch安装）已经完成了es的安装，那么接下来，将介绍下如在java代码中完成对某个索引的类型的文档的增删改查。这个java api的介绍在官网上也有很好的例子，大家可以参考下。 
完整演示demo下载：
github:https://github.com/wesley52">
<meta property="og:type" content="article">
<meta property="og:title" content="ElasticSearch JAVA API基础学习------Elasticsearch学习（二）">
<meta property="og:url" content="http://zhengweishan.oschina.io/2017/01/19/es2/index.html">
<meta property="og:site_name" content="迷失的男孩">
<meta property="og:description" content="ElasticSearch JAVA API基础学习——Elasticsearch学习（二）在上一篇博客中（Elasticsearch安装）已经完成了es的安装，那么接下来，将介绍下如在java代码中完成对某个索引的类型的文档的增删改查。这个java api的介绍在官网上也有很好的例子，大家可以参考下。 
完整演示demo下载：
github:https://github.com/wesley52">
<meta property="og:updated_time" content="2017-01-20T05:32:38.031Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ElasticSearch JAVA API基础学习------Elasticsearch学习（二）">
<meta name="twitter:description" content="ElasticSearch JAVA API基础学习——Elasticsearch学习（二）在上一篇博客中（Elasticsearch安装）已经完成了es的安装，那么接下来，将介绍下如在java代码中完成对某个索引的类型的文档的增删改查。这个java api的介绍在官网上也有很好的例子，大家可以参考下。 
完整演示demo下载：
github:https://github.com/wesley52">
    

    
        <link rel="alternate" href="/atom.xml" title="迷失的男孩" type="application/atom+xml" />
    

    
        <link rel="icon" href="/css/images/favicon.ico" />
    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">
    <link rel="alternate stylesheet" href="http://cdn.bootcss.com/highlight.js/8.0/styles/monokai_sublime.min.css" title="highlight" />
    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    
        <script>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?eb23f1849f20e62c924d275e4edef134";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>

    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">迷失的男孩</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">主页</a>
                
                    <a class="main-nav-link" href="/archives">归档</a>
                
                    <a class="main-nav-link" href="/categories">分类</a>
                
                    <a class="main-nav-link" href="/tags">标签</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.jpg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/.">主页</a></td>
                
                    <td><a class="main-nav-link" href="/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.jpg" />
            <h2 id="name">迷失的男孩</h2>
            <h3 id="title">为API生，为框架死，为debug奋斗一辈子，吃符号亏，上大小写的当，最后死在需求上。</h3>
            <span id="location"><i class="fa fa-map-marker"></i>中国, 北京</span>
            <a id="follow" target="_blank" href="https://github.com/wesley5201314">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                25
                <span>文章</span>
            </div>
            <div class="article-info-block">
                13
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="https://github.com/wesley5201314" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="https://git.oschina.net/zhengweishan" target="_blank" title="git" class=tooltip>
                            <i class="fa fa-git"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/css/images/weixin.png" target="_blank" title="weixin" class=tooltip>
                            <i class="fa fa-weixin"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="http://weibo.com/wesley5201314" target="_blank" title="weibo" class=tooltip>
                            <i class="fa fa-weibo"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
        <div class="base-info" style="text-align:center">
        <span style="color:#38b7ea">今天是：
                 <script type="text/javascript">
                　　today=new Date(); 
                    var tdate,tday, x,year; 
                    var x = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五","星期六");
                　　var MSIE=navigator.userAgent.indexOf("MSIE");
                    if(MSIE != -1)
                    　year =(today.getFullYear());
                    else
                    　year = (today.getYear()+1900);
                    　tdate= year+ "年" + (today.getMonth() + 1 ) + "月" + today.getDate() + "日" + " " + x[today.getDay()];
                    　document.write(tdate); 
                </script>
        </span> 
        </div>
        <div class="base-info" style="text-align:center">
                <span style="color:#38b7ea;"><script type="text/javascript">
                    today=new Date();
                    var day; var date; var hello;
                    hour=new Date().getHours()
                    if(hour < 6)hello='  凌晨好! '
                    else if(hour < 9)hello=' 早上好! '
                    else if(hour < 12)hello=' 上午好! '
                    else if(hour < 14)hello=' 中午好! '
                    else if(hour < 17)hello=' 下午好! '
                    else if(hour < 19)hello=' 傍晚好! '
                    else if(hour < 22)hello=' 晚上好! '
                    else {hello='夜深了! '}
                    var webUrl = webUrl;
                    document.write(' '+hello);
                </script>
                </span>
            <span id="busuanzi_container_site_uv">
                您是本站第<span id="busuanzi_value_site_uv" class="foot-count"></span>位访客
            </span>
        </div>
    </div>
</aside>

            
            <section id="main"><article id="post-es2" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            ElasticSearch JAVA API基础学习------Elasticsearch学习（二）
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/2017/01/19/es2/">
            <time datetime="2017-01-18T16:00:00.000Z" itemprop="datePublished">2017-01-19</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/Elasticsearch/">Elasticsearch</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/Elasticsearch学习/">Elasticsearch学习</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <h1 id="ElasticSearch-JAVA-API基础学习——Elasticsearch学习（二）"><a href="#ElasticSearch-JAVA-API基础学习——Elasticsearch学习（二）" class="headerlink" title="ElasticSearch JAVA API基础学习——Elasticsearch学习（二）"></a>ElasticSearch JAVA API基础学习——Elasticsearch学习（二）</h1><p>在上一篇博客中（<a href="https://my.oschina.net/zhengweishan/blog/823856" target="_blank" rel="external">Elasticsearch安装</a>）已经完成了<a href="https://my.oschina.net/zhengweishan/blog/823856" target="_blank" rel="external">es的安装</a>，那么接下来，将介绍下如在java代码中完成对某个索引的类型的文档的增删改查。这个java api的介绍在官网上也有很好的例子，大家可以参考下。 </p>
<p>完整演示demo下载：</p>
<p>github:<a href="https://github.com/wesley5201314/Elasticsearch-demo" target="_blank" rel="external">https://github.com/wesley5201314/Elasticsearch-demo</a></p>
<p>gitosc:<a href="https://git.oschina.net/zhengweishan/Elasticsearch-demo" target="_blank" rel="external">https://git.oschina.net/zhengweishan/Elasticsearch-demo</a></p>
<p>es中的索引就对应数据库，类型就对应着数据库中的表，文档就对应着数据库表中的记录，因此，我们首先得创建一个索引，然后，再创建一个类型，这个类型会包含字段类型信息，然后就可以在这个索引上对此类型的文档进行增删改查了。 </p>
<p>下面，将分步介绍：<a id="more"></a></p>
<p>创建一个EsClient.java类，直接贴出代码如下：</p>
<pre><code>package com.es.demo;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Properties;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class EsClient {

    /** 配置文件参数 */
    private static Properties properties = null;

    private static String es_ip = null; //ip
    private static int es_port = 0; //端口
    private static String es_cluster_name = null; //集群名字

    private static TransportClient client = null;

    public TransportClient getClient() throws IOException{
        properties = new Properties();
        properties.load(TransportClient.class.getClassLoader().getResourceAsStream(&quot;env.properties&quot;));

        es_ip = properties.getProperty(&quot;target.es.ip&quot;);
        es_port = Integer.valueOf(properties.getProperty(&quot;target.es.port&quot;));
        es_cluster_name = properties.getProperty(&quot;target.es.cluster.name&quot;);
        System.out.println(&quot;原始地址，es_ip = &quot;+es_ip);
        String [] hosts = es_ip.split(&quot;,&quot;);
        System.out.println(&quot;切割之后的esIp数组  = &quot;+hosts);//针对于以后的集群部署我这里只有 一台服务器

        Settings settings = Settings.settingsBuilder()
                .put(&quot;cluster.name&quot;,es_cluster_name)
        .put(&quot;client.transport.sniff&quot;, true).build();
        client = TransportClient.builder().settings(settings)
                .build();
        for(int i=0;i&lt;hosts.length;i++){
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hosts[i]), es_port));
        }
        return client;
    } 

}
</code></pre><p>然后创建一个实体类Test.java对应es中的数据</p>
<pre><code>package com.es.demo;

public class Test {

    private String author;
    private String content;
    private String title;
    private String category;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return &quot;Test [author=&quot; + author + &quot;, content=&quot; + content + &quot;, title=&quot; + title + &quot;, category=&quot; + category + &quot;]&quot;;
    }

}
</code></pre><p>然后再提供一个转换工具类（此类不是多好，有好的大家可以提供下）：</p>
<pre><code>package com.es.demo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
/**
 * 
 * &lt;br&gt;
 * 标题: map转成bean&lt;br&gt;
 * 描述: &lt;br&gt;
 * 公司: www.tydic.com&lt;br&gt;
 * @autho wesley
 * @time 2016年10月31日 下午5:03:08
 */
public class ConverterUtil {

    /** 转换为驼峰（大写）
     * 
     * @param underscoreName
     * @return */
    public static String camelCaseName(String underscoreName) {
        StringBuilder result = new StringBuilder();
        if (underscoreName != null &amp;&amp; underscoreName.length() &gt; 0) {
            boolean flag = false;
            for (int i = 0; i &lt; underscoreName.length(); i++) {
                char ch = underscoreName.charAt(i);
                if (&quot;_&quot;.charAt(0) == ch) {
                    flag = true;
                }
                else {
                    if (flag) {
                        result.append(Character.toUpperCase(ch));
                        flag = false;
                    }
                    else {
                        result.append(Character.toLowerCase(ch));
                    }
                }
            }
        }
        return result.toString();
    }

    /** 转换为下划线(大写)
     * 
     * @param camelCaseName
     * @return */
    public static String underscoreName(String camelCaseName) {
        StringBuilder result = new StringBuilder();
        int len = camelCaseName.length();
        if (camelCaseName != null &amp;&amp; len &gt; 0) {
            result.append(camelCaseName.substring(0, 1).toUpperCase());
            for (int i = 1; i &lt; len; i++) {
                char ch = camelCaseName.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append(&quot;_&quot;);
                    result.append(ch);
                }
                else {
                    result.append(Character.toUpperCase(ch));
                }
            }
        }
        return result.toString();
    }

    /** 把Map&lt;String,Object&gt;处理成实体类
     * 
     * @param clazz
     *想要的实体类
     * @param map
     *包含信息的Map对象
     * @return */
    @SuppressWarnings({ &quot;unchecked&quot;, &quot;rawtypes&quot; })
    public static Object mapToObject(Class clazz, Map&lt;String, Object&gt; map) {
        if (null == map) {
            return null;
        }
        Field[] fields = clazz.getDeclaredFields(); // 取到类下所有的属性，也就是变量名
        Field field;
        Object o = null;
        try {
            o = clazz.newInstance();
        }
        catch (InstantiationException e1) {
            e1.printStackTrace();
        }
        catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
        for (int i = 0; i &lt; fields.length; i++) {
            field = fields[i];
            String fieldName = field.getName();
            // 把属性的第一个字母处理成大写
            String stringLetter = fieldName.substring(0, 1).toUpperCase();
            // 取得set方法名，比如setBbzt
            String setterName = &quot;set&quot; + stringLetter + fieldName.substring(1);
            // 真正取得set方法。
            Method setMethod = null;
            Class fieldClass = field.getType();
            try {
                if (isHaveSuchMethod(clazz, setterName)) {
                    if (fieldClass == String.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, String.valueOf(map.get(fieldName)));// 为其赋值
                        }
                    }
                    else if (fieldClass == Integer.class || fieldClass == int.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, Integer.parseInt(String.valueOf(map.get(fieldName))));// 为其赋值
                        }

                    }
                    else if (fieldClass == Boolean.class || fieldClass == boolean.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, Boolean.getBoolean(String.valueOf(map.get(fieldName))));// 为其赋值
                        }

                    }
                    else if (fieldClass == Short.class || fieldClass == short.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, Short.parseShort(String.valueOf(map.get(fieldName))));// 为其赋值
                        }

                    }
                    else if (fieldClass == Long.class || fieldClass == long.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, Long.parseLong(String.valueOf(map.get(fieldName))));// 为其赋值
                        }

                    }
                    else if (fieldClass == Double.class || fieldClass == double.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, Double.parseDouble(String.valueOf(map.get(fieldName))));// 为其赋值
                        }

                    }
                    else if (fieldClass == Float.class || fieldClass == float.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, Float.parseFloat(String.valueOf(map.get(fieldName))));// 为其赋值
                        }

                    }
                    else if (fieldClass == BigInteger.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, BigInteger.valueOf(Long.parseLong(String.valueOf(map.get(fieldName)))));// 为其赋值
                        }

                    }
                    else if (fieldClass == BigDecimal.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            setMethod.invoke(o, BigDecimal.valueOf(Long.parseLong(String.valueOf(map.get(fieldName)))));// 为其赋值
                        }

                    }
                    else if (fieldClass == Date.class) {
                        setMethod = clazz.getMethod(setterName, fieldClass);
                        if (null != map.get(fieldName) &amp;&amp; !(&quot;&quot;).equals(map.get(fieldName))) {
                            DateTime date = ISODateTimeFormat.dateTimeParser().parseDateTime((String) map.get(fieldName));
                            setMethod.invoke(o, new Date(date.getMillis()));// 为期赋值
                        }
                        /*
                         * if (map.get(fieldName).getClass() == java.sql.Date.class) { setMethod.invoke(o, new Date(((java.sql.Date)
                         * map.get(fieldName)).getTime()));// 为其赋值 } else if (map.get(fieldName).getClass() ==
                         * java.sql.Time.class) { setMethod.invoke(o, new Date(((java.sql.Time) map.get(fieldName)).getTime()));// 为其赋值 } else
                         * if (map.get(fieldName).getClass() == java.sql.Timestamp.class) { setMethod.invoke(o, new Date(((java.sql.Timestamp)
                         * map.get(fieldName)).getTime()));// 为其赋值 }else if(map.get(fieldName).getClass() ==
                         * org.joda.time.format.ISODateTimeFormat.class){ DateTime date =
                         * ISODateTimeFormat.dateTimeParser().parseDateTime((String)map.get(fieldName)); setMethod.invoke(o, new
                         * Date(date.getMillis())); }
                         */
                    }
                }
            }
            catch (SecurityException e) {
                e.printStackTrace();
            }
            catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
            }

        }
        return o;
    }

    /** 判断某个类里是否有某个方法
     * 
     * @param clazz
     * @param methodName
     * @return */
    public static boolean isHaveSuchMethod(Class&lt;?&gt; clazz, String methodName) {
        Method[] methodArray = clazz.getMethods();
        boolean result = false;
        if (null != methodArray) {
            for (int i = 0; i &lt; methodArray.length; i++) {
                if (methodArray[i].getName().equals(methodName)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.err.println(underscoreName(&quot;name_full&quot;));
        System.err.println(camelCaseName(&quot;NAME_FILL&quot;));
        System.err.println(camelCaseName(&quot;nameFill&quot;));
        System.err.println(underscoreName(&quot;nameFill&quot;));
    }
}
</code></pre><p>暂时没有封装，直接用main学习演示基本操作的的，代码如下：</p>
<pre><code>package com.es.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.ActionWriteResponse.ShardInfo;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException
    {

        EsClient esClient = new EsClient();
        TransportClient client = esClient.getClient();
        //---------------演示查询
       /* SearchRequestBuilder request = client.prepareSearch(&quot;wesley&quot;)
                .setTypes(&quot;test&quot;).setSearchType(SearchType.QUERY_THEN_FETCH);
        //初始化查询参数
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery(&quot;author&quot;,&quot;author&quot;));
        request.setQuery(query);
        //查询操作
        SearchResponse response = request.execute().actionGet();
        List&lt;Test&gt; returnList = new ArrayList&lt;Test&gt;();
        SearchHits hints = response.getHits();
        for(SearchHit theHit : hints){// 每条纪录
            Map&lt;String,Object&gt; testInfo = new HashMap&lt;String,Object&gt;();
            for(Map.Entry&lt;String, Object&gt; entity : theHit.getSource().entrySet()){
                testInfo.put(entity.getKey(), entity.getValue()==null ? null : entity.getValue().toString());// 根据数值大小，value 可能为Integer/Long 不依赖ES映射类型
            }
            returnList.add((Test)ConverterUtil.mapToObject(Test.class, testInfo));
        }

        for(Test test:returnList){
            System.out.println(&quot;-----------------&quot;+test);
        }*/
        //---------------演示查询------------end

        //-----------演示创建索引,类型,文档-----------
        /*ObjectMapper objectMapper = new ObjectMapper();
        Test test = new Test();
        test.setAuthor(&quot;author6&quot;);
        test.setCategory(&quot;category6&quot;);
        test.setTitle(&quot;title6&quot;);
        test.setContent(&quot;content6&quot;);
        String source = objectMapper.writeValueAsString(test);
        System.out.println(&quot;--------&quot;+source);
        IndexRequestBuilder indexBuilder = client.prepareIndex().setIndex(&quot;wesley6&quot;).setType(&quot;test6&quot;).setSource(source);
        IndexResponse indexResponse = indexBuilder.execute().actionGet();
        System.out.println(&quot;--------&quot;+indexResponse.isCreated()+&quot;----------&quot;);*/
        //-----------演示创建索引,类型,文档-----------end
        //------------演示删除文档-------
        /*DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete(&quot;wesley6&quot;, &quot;test6&quot;, &quot;AVmV5176AmysSwOEBaDt&quot;);
        DeleteResponse deleteResponse = deleteRequestBuilder.execute().actionGet();
        System.out.println(&quot;------isDelete-----&quot;+deleteResponse.isFound());*/
        //------------演示删除文档-------end
        //------------演示删除指定索引-------
        /*DeleteIndexRequestBuilder deleteRequestBuilder = client.admin().indices().prepareDelete(&quot;wesley6&quot;);
        DeleteIndexResponse deleteResponse = deleteRequestBuilder.execute().actionGet();
        System.out.println(&quot;------isDelete-----&quot;+deleteResponse.isAcknowledged());*/
        //------------演示删除指定索引-------end
        //----------演示创建索引，类型
        // 使用XContentBuilder创建Mapping
        /*XContentBuilder builder = 
            XContentFactory.jsonBuilder()
                            .startObject()
                                .field(&quot;properties&quot;)
                                    .startObject()
                                        .field(&quot;name&quot;)
                                            .startObject()
                                                .field(&quot;index&quot;, &quot;not_analyzed&quot;)
                                                .field(&quot;type&quot;, &quot;string&quot;)
                                            .endObject()
                                        .field(&quot;age&quot;)
                                            .startObject()
                                                .field(&quot;index&quot;, &quot;not_analyzed&quot;)
                                                .field(&quot;type&quot;, &quot;integer&quot;)
                                            .endObject()
                                    .endObject()
                            .endObject();
        System.out.println(builder.string());  
        //创建索引
        CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(&quot;wesley00&quot;);
        CreateIndexResponse createIndexResponse = createIndexRequestBuilder.execute().actionGet();
        System.out.println(&quot;------isCreated----&quot;+createIndexResponse.isAcknowledged());
        //创建type
        PutMappingRequest mappingRequest = Requests.putMappingRequest(&quot;wesley00&quot;).source(builder).type(&quot;user&quot;);
        PutMappingResponse putMappingResponse = client.admin().indices().putMapping(mappingRequest).actionGet();
        System.out.println(&quot;------isCreated----&quot;+putMappingResponse.isAcknowledged());*/
        //----------演示创建索引，类型---end
        //---------演示更新文档----
        XContentBuilder builder = 
                XContentFactory.jsonBuilder()
                                .startObject()
                                    .field(&quot;author&quot;, &quot;lisi&quot;)
                                    .field(&quot;title&quot;, &quot;update111&quot;)
                                    .field(&quot;content&quot;,&quot;111111&quot;)
                                    .field(&quot;category&quot;,&quot;category-update&quot;)
                                .endObject();
            UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate().setIndex(&quot;wesley&quot;).setType(&quot;test&quot;).setDoc(builder).setId(&quot;1111&quot;);
            System.out.println(&quot;----------&quot;+updateRequestBuilder);
            UpdateResponse updateResponse = updateRequestBuilder.execute().actionGet();
            System.out.println(&quot;---------&quot;+updateResponse);
            //说明isCreated这个方法如果返回的是true说明原来没有数据重新创建了，如果返回false说明更新成功。不知道他们为什么这么设计。
            //Returns true if document was created due to an UPSERT operation 源码中的注释说明。
            System.out.println(&quot;---------&quot;+updateResponse.isCreated()+&quot;---version-&quot;+updateResponse.getVersion()+&quot;-------------&quot;); //
        ////---------演示更新文档----end--
    }
}
</code></pre><p>最后，稍作总结，上面都是只贴出了代码，也没给出比较详细的解释，这个大家可以参考着官网的介绍，然后结合贴出的代码，估计就能够看懂了。另外，还有其它java api比如聚合查询，暂时也没去研究，大家可以去学习下，我也是刚学，有啥问题的地方欢迎指出，谢谢！</p>
<p>ElasticSearch2.x API变化官网链接<br><a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.3/breaking-changes-2.0.html" target="_blank" rel="external">https://www.elastic.co/guide/en/elasticsearch/reference/2.3/breaking-changes-2.0.html</a></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    
        <a href="http://zhengweishan.oschina.io/2017/01/19/es2/#comments" class="article-comment-link disqus-comment-count" data-disqus-url="http://zhengweishan.oschina.io/2017/01/19/es2/">评论</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/2017/01/20/GC/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    JAVA垃圾回收机制
                
            </div>
        </a>
    
    
        <a href="/2017/01/19/es1/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">Elasticsearch安装与Elasticsearch-Head插件安转(windows环境)------Elasticsearch学习（一）</div>
        </a>
    
</nav>


    
</article>


    
    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>

</section>
            
                <aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="">
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/03/27/CountDownLatch/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/并发/">并发</a></p>
                            <p class="item-title"><a href="/2017/03/27/CountDownLatch/" class="title">java并发包里的CountDownLatch的用法</a></p>
                            <p class="item-date"><time datetime="2017-03-26T16:00:00.000Z" itemprop="datePublished">2017-03-27</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/03/24/spring-boot-demo/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot/">SpringBoot</a></p>
                            <p class="item-title"><a href="/2017/03/24/spring-boot-demo/" class="title">spring boot + mybatis + quartz + druid + swagger2</a></p>
                            <p class="item-date"><time datetime="2017-03-23T16:00:00.000Z" itemprop="datePublished">2017-03-24</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/03/23/boy-rpc-framework/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/rpc/">rpc</a></p>
                            <p class="item-title"><a href="/2017/03/23/boy-rpc-framework/" class="title">分布式rpc框架</a></p>
                            <p class="item-date"><time datetime="2017-03-22T16:00:00.000Z" itemprop="datePublished">2017-03-23</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/02/10/（六）Tomcat_7.0.70生命周期管理/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/Tomcat源码/">Tomcat源码</a></p>
                            <p class="item-title"><a href="/2017/02/10/（六）Tomcat_7.0.70生命周期管理/" class="title">Tomcat源码学习（六）--Tomcat_7.0.70 生命周期管理</a></p>
                            <p class="item-date"><time datetime="2017-02-09T16:00:00.000Z" itemprop="datePublished">2017-02-10</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/02/09/（五）Tomcat_7.0.70类加载体系/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/Tomcat源码/">Tomcat源码</a></p>
                            <p class="item-title"><a href="/2017/02/09/（五）Tomcat_7.0.70类加载体系/" class="title">Tomcat源码学习（五）-- Tomcat_7.0.70 类加载体系分析</a></p>
                            <p class="item-date"><time datetime="2017-02-08T16:00:00.000Z" itemprop="datePublished">2017-02-09</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Elasticsearch/">Elasticsearch</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA/">JAVA</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JMS/">JMS</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JVM/">JVM</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot/">SpringBoot</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat源码/">Tomcat源码</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/kafka/">kafka</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/rpc/">rpc</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/并发/">并发</a><span class="category-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/ActiveMQ/" style="font-size: 16.67px;">ActiveMQ</a> <a href="/tags/Elasticsearch学习/" style="font-size: 13.33px;">Elasticsearch学习</a> <a href="/tags/GC/" style="font-size: 13.33px;">GC</a> <a href="/tags/Hexo/" style="font-size: 10px;">Hexo</a> <a href="/tags/JAVA/" style="font-size: 16.67px;">JAVA</a> <a href="/tags/JMS/" style="font-size: 16.67px;">JMS</a> <a href="/tags/JVM/" style="font-size: 13.33px;">JVM</a> <a href="/tags/Reflection/" style="font-size: 10px;">Reflection</a> <a href="/tags/SpingBoot/" style="font-size: 10px;">SpingBoot</a> <a href="/tags/kafka/" style="font-size: 16.67px;">kafka</a> <a href="/tags/rpc-分布式/" style="font-size: 10px;">rpc 分布式</a> <a href="/tags/tomcat/" style="font-size: 20px;">tomcat</a> <a href="/tags/并发，CountDownLatch/" style="font-size: 10px;">并发，CountDownLatch</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
                        <a href="http://hexo.io">Hexo</a>
                    </li>
                
                    <li>
                        <a href="https://longfeizheng.github.io/">龙飞</a>
                    </li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>
            
        </div>
        <footer id="footer">
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2017 郑伟山 版权所有<br> 
            由 <a href="http://hexo.io/" target="_blank">Hexo</a> 强力驱动 &brvbar; 主题 -- <a href="https://github.com/ppoffice/hexo-theme-icarus">Icarus</a><br>
            
        </div>
		<div class="inner">
        	<span id="busuanzi_container_site_pv">
    			本站总访问量<span id="busuanzi_value_site_pv" class="foot-count"></span>次
			</span>
		</div>
    </div>
<script src="http://cdn.bootcss.com/highlight.js/8.0/highlight.min.js"></script>
</footer>
        
    
    <script>
    var disqus_config = function () {
        
            this.page.url = 'http://zhengweishan.oschina.io/2017/01/19/es2/';
        
        this.page.identifier = 'es2';
    };
    (function() { 
        var d = document, s = d.createElement('script');  
        s.src = '//' + 'hexo-theme-icarus' + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>



    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>